/**
 * 菜单JS
 */
angular.module('expertsys.home', [])

    .config(['$stateProvider', '$urlRouterProvider',
        function ($stateProvider, $urlRouterProvider) {
            $stateProvider

                .state('proficient', {
                    url: '/proficient/:eId',
                    templateUrl: exp_templateprefix + 'home/proficient.html',
                    controller: 'ProficientController'
                })
                .state('myquestion', {
                    url: '/myquestion',
                    templateUrl: exp_templateprefix + 'home/myquestion.html',
                    controller: 'MyquestionController'
                })
                .state('pushques', {
                    url: '/pushques/:eId',
                    templateUrl: exp_templateprefix + 'home/pushques.html',
                    controller: 'PushquesController'
                })
                .state('expertcategory', {
                    url: '/expertcategory',
                    templateUrl: exp_templateprefix + 'home/categorys.html',
                    controller: 'ExpertCategoryController'
                })
                .state('moreproficient', {
                    url: '/moreproficient/:eCategory',
                    templateUrl: exp_templateprefix + 'home/moreproficient.html',
                    controller: 'MoreproficientController'
                })

        }])
    .controller('ExpertCategoryController', ['$scope', '$state','ExpertsysService',
        function($scope, $state, ExpertsysService){
            $scope.exp_enturl = projectBaseUrl;
            $scope.expertCategory=[];
            $scope.categorys = [];
            $scope.json = {};
            ExpertsysService.getExpertsysList().$promise.then(function(data){
                for(var i=0; i<data.length; i++){
                    if(data[i].category != null){
                        $scope.expertCategory.push(data[i].category);
                    }
                }
                //去除数组中重复数据
                for(var i = 0; i < $scope.expertCategory.length; i++){
                    if(!$scope.json[$scope.expertCategory[i]]){
                        $scope.categorys.push($scope.expertCategory[i]);
                        $scope.json[$scope.expertCategory[i]] = 1;
                    }
                }
            });
        }
        ])
    .controller('ProficientController', ['$scope', '$state', '$stateParams', 'ExpertsysService', 'ConversationService',
        function ($scope, $state, $stateParams, ExpertsysService, ConversationService) {

            loading_css();
            var resolSum = 0;
            var unResolSum = 0;
            $scope.renderFinish = function () {
                pageLoad(".expert-all", 100);
                delet();
            }

            // 通过专家id得到热门问题
            ExpertsysService.getHotTopicQue($stateParams.eId).$promise.then(function (data_ht) {
                //得到所有用户
                ExpertsysService.getUserList().$promise.then(function (data_allu) {
                    //通过专家id得到所有问题
                    ExpertsysService.getTopicQueByEid($stateParams.eId).$promise.then(function (data_t) {
                        //得到所有问答
                        ConversationService.getConversation().$promise.then(function (data_c) {
                            //统计主题中的问答数
                            $scope.getConverSum = function (data) {
                                var sum = 0;
                                for (var a = 0; a < data_c.length; a++) {
                                    if (data == data_c[a].topicid) {
                                        sum++;
                                    }
                                }
                                return sum;
                            }
                            $scope.hotQueList = [];
                            $scope.resolQueList = [];
                            $scope.unresolQueList = [];
                            //统计出已决解和未解决的问题数
                            for (var i = 0; i < data_t.length; i++) {
                                for (var k = 0; k < data_allu.length; k++) {
                                    if (data_t[i].userid == data_allu[k].userid) {
                                        if (data_t[i].state == 0) {
                                            $scope.unresol_converSum = $scope.getConverSum(data_t[i].topicid);
                                            $scope.unresolQueList.push({
                                                'tid': data_t[i].topicid,
                                                'tName': data_t[i].topicname,
                                                'cTime': data_t[i].createtime,
                                                'converSum': $scope.unresol_converSum,
                                                'uName': data_allu[k].name,
                                                'uLogo': data_allu[k].logo
                                            })
                                            unResolSum++;
                                        } else {
                                            $scope.resol_converSum = $scope.getConverSum(data_t[i].topicid);
                                            $scope.resolQueList.push({
                                                'tid': data_t[i].topicid,
                                                'tName': data_t[i].topicname,
                                                'cTime': data_t[i].createtime,
                                                'converSum': $scope.resol_converSum,
                                                'uName': data_allu[k].name,
                                                'uLogo': data_allu[k].logo
                                            })
                                            resolSum++;
                                        }
                                        break;
                                    }
                                }

                            }
                            //把专家的个人数据放入expertArray包括已解决和未解决的问题数
                            ExpertsysService.getExpertsysById($stateParams.eId).$promise.then(function (data_e) {
                                ExpertsysService.getUserById($stateParams.eId).$promise.then(function (data_u) {
                                    $scope.expertArray = {
                                        'id': data_e.userid,
                                        'logo': data_u.logo,
                                        'eName': data_u.name,
                                        'ephone': data_u.phone,
                                        'tag': data_e.tag,
                                        'experience': data_e.experience,
                                        'introduction': data_e.introduction,
                                        'profession': data_e.profession,
                                        'resolSum': resolSum,
                                        'unResolSum': unResolSum,
                                        'sum': resolSum + unResolSum
                                    };
                                    if ($scope.expertArray.sum == 0) {
                                        $(".spinner").hide();
                                        $(".expert-all").fadeIn();
                                    }
                                });
                            });
                            //repeat 热门问题
                            for (var z = 0; z < data_ht.length; z++) {
                                $scope.converSum = $scope.getConverSum(data_ht[z].topicid);
                                for (var j = 0; j < data_allu.length; j++) {
                                    if (data_ht[z].userid == data_allu[j].userid) {
                                        $scope.hotQueList.push({
                                            'tid': data_ht[z].topicid,
                                            'tName': data_ht[z].topicname,
                                            'cTime': data_ht[z].createtime,
                                            'converSum': $scope.converSum,
                                            'uName': data_allu[j].name,
                                            'uLogo': data_allu[j].logo
                                        });
                                        break;
                                    }
                                }
                            }
                        });
                    });
                });
            });

            $("#resDiv").hide();
            $("#unresDiv").hide();

            $scope.showResDiv = function () {
                $("#pro_details").hide();
                $("#unresDiv").hide();
                $("#resDiv").show();
                $("#res_li").addClass("res_li1");
                $("#unres_li").removeClass("res_li1");
            }
            $scope.showUnresDiv = function () {
                $("#pro_details").hide();
                $("#resDiv").hide();
                $("#unresDiv").show();
                $("#res_li").removeClass("res_li1");
                $("#unres_li").addClass("res_li1");
            }
            $scope.showDetDiv = function () {
                $("#pro_details").show();
                $("#resDiv").hide();
                $("#unresDiv").hide();
                $("#res_li").removeClass("res_li1");
                $("#unres_li").removeClass("res_li1");
            }
        }
    ])
    .controller('MyquestionController', ['$scope', '$state', 'ExpertsysService', 'ConversationService', 'ExpAuthService',
        function ($scope, $state, ExpertsysService, ConversationService, ExpAuthService) {
            $scope.uId = ExpAuthService.getUserid();
            loading_css();
            $scope.exp_enturl = projectBaseUrl;
            if ($scope.uId == 0) {
                window.location.href = projectBaseUrl + "login/";
            }
            $scope.renderFinish = function () {
                pageLoad(".myquestion_mesg");
                delet();
            }
            $scope.load_myque = function () {
                ExpertsysService.getTOpicQueByUid($scope.uId).$promise.then(function (data_ut) {
                    ExpertsysService.getUserById($scope.uId).$promise.then(function (data_u) {
                        ConversationService.getConversation().$promise.then(function (data_c) {
                            $scope.u_topicQueList = [];
                            for (var i = 0; i < data_ut.length; i++) {
                                $scope.u_converSum = 0;
                                for (var j = 0; j < data_c.length; j++) {
                                    if (data_c[j].topicid == data_ut[i].topicid) {
                                        $scope.u_converSum++;
                                    }
                                }
                                $scope.u_topicQueList.push({
                                    'tid': data_ut[i].topicid,
                                    'tName': data_ut[i].topicname,
                                    'cTime': data_ut[i].createtime,
                                    'converSum': $scope.u_converSum,
                                    'uName': data_u.name,
                                    'uLogo': data_u.logo
                                });
                            }
                            if ($scope.u_topicQueList.length == 0) {
                                $(".spinner").hide();
                                $(".myquestion_mesg").fadeIn();
                            }
                        });
                    });
                });
            }
            $scope.load_myque();
            dismiss();
            $scope.myque_remove = function (myque_tid) {
                $(".contain-item").fadeIn();
                $scope.myque_sure = function () {
                    ExpertsysService.removeTopicQueByTid(myque_tid).$promise.then(function (data_t) {
                        ConversationService.getConversationById(myque_tid).$promise.then(function (data_c) {
                            if (data_c.length != 0) {
                                //删除问题的问答
                                ConversationService.conver_removeByTid(myque_tid);
                            }
                            $(".contain-item").fadeOut();
                            $scope.load_myque();
                        });

                    });
                }
            }
        }])
    .controller('PushquesController', ['$scope', '$state', '$stateParams', 'PushQuesService', 'ExpAuthService',
        function ($scope, $state, $stateParams, PushQuesService, ExpAuthService) {
            dismiss();
            $scope.userid = ExpAuthService.getUserid();
            if ($scope.userid == 0) {
                window.location.href = projectBaseUrl + "login/";
            }
            var success_func = function () {
                input_alert("提交成功");
                setTimeout(function () {
                    $state.go("myquestion");
                }, 1000)
            }
            var error_func = function () {
                input_alert("提交失败");
            }
            $scope.textchange = function (text_length) {
                if ($scope.topic.topicname != undefined && $scope.topic.topicname.length > text_length) {
                    $scope.topic.topicname = $scope.topic.topicname.substring(0, text_length);
                    input_alert("主题内容超过" + text_length + "字")
                }
                if ($scope.topic_detail != undefined && $scope.topic_detail.length > text_length) {
                    $scope.topic_detail = $scope.topic_detail.substring(0, text_length);
                    input_alert("主题内容超过" + text_length + "字")
                }
            }
            $scope.filesList = [];//存储files对象
            //在界面显示要上传的多图片
            $scope.setImage = function (obj) {
                var i = 0;
                var a = 0;
                var ul_in = document.getElementById("push_liImage");
                if (obj.files.length == 0) {
                    return;
                }
                var fileList = obj.files;
                //校验图片
                if (checkPic(obj) == 1) {
                    return;
                }
                if (fileList.length > 3) {
                    input_alert("图片最多只能传3张", 2000);
                    return;
                }
                $scope.deal_picture = function () {
                    if (fileList[i]) {
                        $scope.filesList.push(fileList[i]);
                        a = $scope.filesList.length;
                        if (fileList[i].size > 2097152) {
                            input_alert("上传图片最大为2M", 2000);
                            return;
                        }
                        var reader = new FileReader();
                        reader.onload = function (evt) {
                            // 处理下配置参数和格式的html
                            ul_in.innerHTML += "<li id=" + a + " class='fatu1' style='float:left' onclick=angular.element(this).scope().remove_picture(this," + a + ")><img src=" + evt.target.result + ">";

                            i++;
                            // 再接着调用此方法递归组成可以预览的html
                            var arrLi = ul_in.getElementsByTagName('li');
                            if (arrLi.length == 3) {
                                $("#add_imageButton").hide();
                                return;
                            }
                            $scope.deal_picture();
                        }
                        reader.readAsDataURL(fileList[i]);
                    } else {
                        return;
                    }
                }
                $scope.deal_picture();
            }
            //上传图片
            $scope.uplo_pictuers = function () {
                if ($("#exp_ztName").val() == "") {
                    input_alert("请输入主题", 2000);
                    return;
                }
                var picture = document.getElementById("push_liImage");
                var arrLi = picture.getElementsByTagName('li');
                $scope.arrSrc = "";
                if (arrLi.length == 0) {
                    $scope.addCompleteQue($scope.arrSrc);
                    return;
                }
                var i = 0;
                $scope.abc = function () {
                    var push_img = arrLi[i].getElementsByTagName('img');
                    var b = arrLi[i].id;//$scope.filesList数组的的下标
                    $scope.imageSrc = push_img[0].src;
                    $scope.files = $scope.filesList[b - 1];
                    $scope.imageName = $scope.filesList[b - 1].name;
                    PushQuesService.uploadFile($scope.imageSrc, $scope.files, $scope.imageName).then(function (data) {
                        $scope.arrSrc += "{{img:" + data;
                        i++;
                        if (i < arrLi.length) {
                            $scope.abc();
                        } else {
                            // 走到这里说明图片已经上传完毕
                            $scope.filesList = [];
                            $scope.addCompleteQue($scope.arrSrc);
                            return;
                        }
                    });
                }
                $scope.abc();
            };
            //上传问题+图片路径
            $scope.topic = "";
            $scope.addCompleteQue = function (strUrl) {
                $scope.topic.topicid = new Date().getTime();
                $scope.topic.expert = $stateParams.eId;
                $scope.topic.state = 0;
                $scope.topic.userid = $scope.userid;
                $scope.topic.detail = $("#topic_detail").val() + strUrl;
                PushQuesService.addTopicQue($scope.topic, success_func, error_func).$promise.then(function (data_t) {
                });
            };
            //删除图片
            var remove_liObj = null;// 记录要删除的obj对象
            var mark = "";// 记录要删除图片的$scope.filesList数组的下标
            $scope.remove_picture = function (obj, a) {
                remove_liObj = "";
                $(".contain-item").fadeIn();
                remove_liObj = obj
                mark = a - 1;
            }
            $scope.remove_sure = function () {
                remove_liObj.remove();
                delete $scope.filesList[mark];
                //$scope.filesList.splice(mark,1);
                $(".contain-item").fadeOut();
                var ul_in = document.getElementById("push_liImage");
                var arrLi = ul_in.getElementsByTagName('li');
                if (arrLi.length < 3) {
                    $("#add_imageButton").show();
                }
            }

        }])

    .controller('MoreproficientController', ['$scope', '$state', '$stateParams', 'ExpertsysService',
        function ($scope, $state, $stateParams, ExpertsysService) {
            $scope.category = $stateParams.eCategory;
            loading_css();
            $scope.exp_enturl = projectBaseUrl;
            $scope.moreproList = [];
            $scope.page = {
                n: 0,
                num: 3
            }
            var maxLen = 0;
            $scope.flat = true;

            //初始化限制加载条数
            $scope.load = function () {
                //加载显示专家(有限制)
                $(".under-span").attr("disabled", "true");
                $(".under-span").html("疯狂加载中......");
                ExpertsysService.getExpertsysByPage($scope.page.n, $scope.page.num,$stateParams.eCategory).$promise.then(function (data_e) {
                    //得到所有User
                    ExpertsysService.getUserList().$promise.then(function (data_u) {
                        //得到所有topic
                        ExpertsysService.getTopicQue().$promise.then(function (data_t) {

                            for (var i = 0; i < data_e.length; i++) {
                                for (var z = 0; z < data_u.length; z++) {
                                    if (data_e[i].userid == data_u[z].userid) {
                                        var sum = 0;
                                        for (var j = 0; j < data_t.length; j++) {
                                            if (data_e[i].userid == data_t[j].expert) {
                                                sum++;//提问数
                                            }
                                        }
                                        $scope.moreproList.push({
                                            'userid': data_e[i].userid,
                                            'name': data_u[z].name,
                                            'logo': data_u[z].logo,
                                            'tag': data_e[i].tag,
                                            'experience': data_e[i].experience,
                                            'profession': data_e[i].profession,
                                            'count': sum
                                        });
                                        break;
                                    }
                                }
                            }
                            $(".under-span").removeAttr("disabled");
                            $(".under-span").html("点击加载更多......");
                            setTimeout(function () {
                                $(".spinner").hide();
                                $(".asker-list").fadeIn();
                            }, 200);
                            $scope.page.n = $scope.page.num + $scope.page.n;
                            if ($scope.page.n > $scope.moreproList.length) {
                                input_alert("没有更多专家了！");
                                $scope.flat = false;
                            }
                        })
                    });


                });
            }
            $scope.load();
            //点击加载更多事件

        }])
;
